<template>
  <el-card shadow="hover" style="margin-bottom: 10px" v-if="user.role!== 'PARTICIPANT'">
    <el-input style="width: 200px" v-model="data.username" placeholder="输入查询名字" prefix-icon="Search"></el-input>
    <el-button type="primary" style="margin-left: 5px" :prefix-icon="Search" @click="loadByName">查询</el-button>
    <el-button type="success" @click="reset">重置</el-button>
    <!-- <el-button type="primary" @click="hadleNewracer">新增</el-button> -->
    <el-button type="danger" @click="deleteBatch">批量删除</el-button>
  </el-card>

  <el-card>
    <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="姓名" prop="username"/>
      <el-table-column label="报名赛事" prop="name"/>
      <el-table-column label="报名情况" prop="status"/>
      <el-table-column label="申请时间">
        <template #default="{row}">
          {{ formatDateTime(row.applyTime) }}
        </template>
      </el-table-column>
      <el-table-column label="手机号" prop="phone"/>
      <el-table-column label="操作" width="250px">
        <template #default="scope">
          <el-button @click="handleUpdate(scope.row)" type="primary" :icon="Edit" circle  v-if="scope.row.status === 'PENDING'"></el-button>
          <el-button @click="handleDelete(scope.row.id)" type="warning" :icon="Delete" circle></el-button>
          <el-button type="primary" @click="getType(scope.row , 'APPROVED')" v-if="scope.row.status === 'PENDING'">同意</el-button>
          <el-button @click="getType(scope.row , 'REJECTED')"  v-if="scope.row.status === 'PENDING'">拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 25px">
      <el-pagination
          @size-change="load"
          @current-change="load"
          v-model:current-page="data.currentPage"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
      />
    </div>
  </el-card>

  <el-dialog v-model="data.FormVisible" title="参赛者报名" width="500px">
    <el-form :model="data.form" style="margin-top: 10px;margin-right: 20px">
      <el-form-item label="姓名" label-width="90px">
        <el-input v-model="data.form.username" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="报名赛事" label-width="90px">
        <el-input v-model="data.form.name" autocomplete="off"/>
      </el-form-item>
      <!-- <el-form-item label="报名情况" label-width="90px">
        <el-select v-model="data.form.status" placeholder="请选择状态">
          <el-option label="PENDING" value="PENDING"/>
          <el-option label="APPROVED" value="APPROVED"/>
          <el-option label="REJECTED" value="REJECTED"/>
          <el-option label="CANCELLED" value="CANCELLED"/>
        </el-select>
      </el-form-item> -->
      <el-form-item label="申请时间" label-width="90px">
<!--        <el-input v-model="data.form.applyTime" autocomplete="off"/>-->
        <el-date-picker
            v-model="data.form.applyTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择申请时间"
            style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="手机号" label-width="90px">
        <el-input v-model="data.form.phone" autocomplete="off"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.FormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {onScopeDispose, reactive,ref} from "vue";
import {Delete, Edit, Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import dayjs from "dayjs";

// 修改日期格式化函数
const formatDateTime = (date) => {
  // 显式指定输入格式
  return date ? dayjs(date, 'YYYY-MM-DDTHH:mm:ss').format('YYYY-MM-DD HH:mm:ss') : '--';
};
const user = ref(JSON.parse(localStorage.getItem('user'))) 
const data = reactive({
  username: '',
  name: '',
  applyTime: '',
  status: '',
  phone: '',
  form: {},
  tableData: [],
  currentPage: 1,
  pageSize: 5,
  total: 0,
  FormVisible: false,
  ids: [],
});

const loadByName = () => {
  data.currentPage = 1;
  request.get('/Registration/SelectRegistrationInformation', {
    params: {
      status: data.status,
      applyTime: data.applyTime,
      phone: data.phone,
      name: data.name,
      pageNum: data.currentPage,
      pageSize: data.pageSize,
      role: 'PARTICIPANT',
      username: data.username.trim(),
    },
  }).then((res) => {
    data.tableData = res.data.list;
    data.total = res.data.total;
  });
};

const load = () => {
  request.get('/Registration/SelectRegistrationInformation', {
    params: {
      pageNum: data.currentPage,
      pageSize: data.pageSize,
      status: data.status,
      username: data.username,
      applyTime: data.applyTime,
      phone: data.phone,
      name: data.name,
      role: 'PARTICIPANT',
      userId: user.value.role =="PARTICIPANT"? user.value.id : null
    },
  }).then((res) => {
    console.log('API响应数据:', res.data.list); // 检查applyTime字段是否存在
    data.tableData = res.data?.list || [];
    data.total = res.data?.total || 0;
  });
};

load();

const reset = () => {
  data.username = '';
  load();
};

const hadleNewracer = () => {
  data.FormVisible = true;
  data.form = {};
};

const save = () => {
  // data.form.id ? update() : add();
  const params = {
    ...data.form,
    startTime: data.form.applyTime ? dayjs(data.form.applyTime).format('YYYY-MM-DD HH:mm:ss') : null,
  };

  const requestMethod = data.form.id ? request.put : request.post;
  requestMethod('/Registration', params).then(res => {
    if (res.code === '200') {
      ElMessage.success("操作成功");
      data.FormVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};
const getType = (row , type) => {
  // data.form.id ? update() : add();
  const params = {
    ...row,
    startTime: row.applyTime ? dayjs(row.applyTime).format('YYYY-MM-DD HH:mm:ss') : null,
    status:type
  };

  request.put('/Registration/updateRegistrationInformation', params).then(res => {
    if (res.code === '200') {
      ElMessage.success("操作成功");
      // data.FormVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};
const add = () => {
  request.post('', data.form).then((res) => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.FormVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const update = () => {
  request.put('', data.form).then((res) => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.FormVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const handleUpdate = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.FormVisible = true;
};

const handleDelete = (id) => {
  ElMessageBox.confirm('您确认删除报名信息吗', '删除确认', { type: 'warning' }).then(() => {
    request.delete(`/Registration/${id}`).then((res) => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        data.FormVisible = false;
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(() => {});
};

const handleSelectionChange = (rows) => {
  data.ids = rows.map((row) => row.id);
};

const deleteBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选择数据');
    return;
  }
  ElMessageBox.confirm('您确认删除所选报名信息吗', '删除确认', { type: 'warning' }).then(() => {
    request.delete('/Registration/batch', { data: data.ids }).then((res) => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        data.FormVisible = false;
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(() => {});
};
</script>

<style scoped>
</style>